package com.api.rc.lobby.domain;

import lombok.Getter;
import lombok.extern.slf4j.Slf4j;

import java.io.Serializable;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author RenQiang
 * @date 2021/7/13
 */
@Slf4j
@Getter
public class LobbyTeam implements Serializable {
    private static final long serialVersionUID = 8976782101736341069L;

    private final int no;
    private final int maxMembers;
    private final ConcurrentHashMap<Long, LobbyPlayer> memberMap;

    public LobbyTeam(int no, int maxMembers) {
        this.no = no;
        this.maxMembers = maxMembers;
        this.memberMap = new ConcurrentHashMap<>(maxMembers);
    }

    public boolean isReady() {
        return this.memberMap.size() == this.maxMembers
                && this.memberMap.values().stream()
                .allMatch(LobbyPlayer::isReady);
    }

    public LobbyPlayer removeMember(Long userId) {
        LobbyPlayer lobbyPlayer = memberMap.remove(userId);
        lobbyPlayer.updateReadyStatus(false);
        return lobbyPlayer;
    }

    public boolean addMember(LobbyPlayer lobbyPlayer) {
        if (this.memberMap.size() < this.maxMembers) {
            memberMap.put(lobbyPlayer.getUserInfo().getId(), lobbyPlayer);
            return true;
        }
        return false;
    }

    public void playerReady(Long userId) {
        LobbyPlayer lobbyPlayer = memberMap.get(userId);
        if (lobbyPlayer != null) {
            lobbyPlayer.updateReadyStatus(true);
        }
    }
}
